import { AdManager } from "../../ads/AdManager";
import { ActionTools } from "../../common/ActionTools";
import { Tools } from "../../common/Tools";
import TouchScale from "../../item/Common/TouchScale";
import { AudioManager1 } from "../../manager/AudioManager1";
import { EventManager } from "../../manager/EventManager";
import { UIManager } from "../../manager/UIManager";
import LevelBase from "../../LevelBase";
import LvItem from "../../LvItem";
import LvItem_1 from "./LvItem_1";
import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM } from "../../base/EnumIndex";
import { ResManager1 } from "../../manager/ResManager1";
import { TOUCH_MOVE_LEN } from "../../base/GameIndex";

const { ccclass, property } = cc._decorator;

/** 普通找茬类关卡 */
@ccclass
export default class LevelPre_1 extends LevelBase {

    @property({ type: cc.Button, displayName: "切换按钮" })
    changeBtn: cc.Button = null;
    @property({ type: cc.Button, displayName: "提示按钮" })
    keyBtn: cc.Button = null;
    @property({ type: cc.Node, displayName: "关闭提示按钮" })
    closeTipBtn: cc.Node = null;

    @property({ type: cc.Node, displayName: "viewBg节点" })
    viewBg: cc.Node = null;
    @property({ type: cc.Node, displayName: "遮罩关卡内容节点" })
    maskNode: cc.Node = null;
    @property({ type: cc.Node, displayName: "完成选项Content" })
    downContent: cc.Node = null;
    @property({ type: cc.Node, displayName: "下方答案节点" })
    downItem: cc.Node = null;

    @property({ type: cc.Node, displayName: "黑条提示框" })
    tipNode: cc.Node = null;

    alterNum: number = 1;    //当前页数
    /** 已经完成数组 */
    finishItemArr: Array<LvItem_1> = [];
    /** 已解锁物品ID */
    onLockItemArr: Array<number> = [];
    /** 当前选中ItemID */
    selectItemID: number = 0;
    /** 本关的交互配置 */
    interJson: any = null;
    huaNode: cc.Node = null;   //本关的节点
    start() {
        cc.macro.ENABLE_MULTI_TOUCH = true;  //是否开起多点触摸
        this.changeBtn.node.active = false;

        EventManager.ins.on(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, this.finishTween, this);
        EventManager.ins.on(EVENT_NAME_ENUM.LOOK_ANSWER_TWEEN, this.addAnswer, this);

        this.initBtnEvents();

    }
    onDestroy(): void {
        super.onDestroy();
        EventManager.ins.off(EVENT_NAME_ENUM.FINISH_INTER_TWEEN, this.finishTween, this);
        EventManager.ins.off(EVENT_NAME_ENUM.LOOK_ANSWER_TWEEN, this.addAnswer, this);
        this.unscheduleAllCallbacks();
    }

    /** 初始化所有按钮事件 */
    initBtnEvents() {
        this.changeBtn.node.on("click", () => {
            if (this.alterNum < this.interJson.changeNum) {
                this.alterNum += 1;
            } else {
                this.alterNum = 1;
            }
            this.setAlterNum(this.alterNum);
        });

        this.keyBtn.node.on("click", () => {
            if (this.selectItemID == 0) {
                return cc.log("找不到答案ID");
            }
            AudioManager1.playClick();
            let keyInfo = this.getConfigForID(this.selectItemID).keyInfo;

            if (this.onLockItemArr.indexOf(this.selectItemID) >= 0) {
                UIManager.ins.showPop("TipUI", BUNDLE_TYPE_ENUM.GAME, keyInfo, true);
            } else {
                AdManager.showVideoAd(() => {
                    this.onLockItemArr.push(this.selectItemID);
                    UIManager.ins.showPop("TipUI", BUNDLE_TYPE_ENUM.GAME, keyInfo, true);
                    this.keyBtn.node.children[1].active = this.onLockItemArr.indexOf(this.selectItemID) < 0
                });
            }
        });


        this.closeTipBtn.on(cc.Node.EventType.TOUCH_START, (touches: cc.Touch) => {
            this.keyBtn.node.active = false;
            this.closeTipBtn.active = false;
        }, this, true);
    }

    init(huaPre: cc.Prefab) {
        this.huaNode = cc.instantiate(huaPre);
        this.maskNode.addChild(this.huaNode);
        this.huaNode.getComponent(TouchScale).maskNode = this.maskNode;
        // 适配
        let widthScale = this.maskNode.width / this.huaNode.width;
        let heightScale = this.maskNode.height / this.huaNode.height;
        this.huaNode.scale = Math.min(widthScale, heightScale);
        
        this.initData();
        this.initAllBtnItem();
        this.initHuaItem();
        this.initTouch();
    }
    /** 通过配置 初始化相关内容 */
    initData() {
        if (this.interJson.isChange) {
            this.changeBtn.node.active = true;
        }
    }
    /** 初始化所有的item */
    async initAllBtnItem() {
        for (let i = 0; i < this.interJson.keyNum; i++) {
            let downItem = cc.instantiate(this.downItem);
            downItem.y = 10;
            let spr = await ResManager1.ins.loadRes("spr/" + this.interJson.itemInfo[i].sprUrl, cc.SpriteFrame, BUNDLE_TYPE_ENUM.LEVEL);
            Tools.setSpriteFrame(downItem.getChildByName("itemSpr"), spr);
            downItem.getChildByName("itemLab").getComponent(cc.Label).string = this.interJson.itemInfo[i].info;
            // Tools.setSpriteState( downItem.getChildByName("itemSpr") , 1 );
            this.downContent.addChild(downItem);
            downItem["config"] = this.interJson.itemInfo[i];
            downItem.getChildByName("lockSpr").on("click", () => {
                this.openTipBtn(downItem);
            });
        }
    }
    /** 根据配置初始化 item */
    initHuaItem() {
        for (let i = 0; i < this.interJson.itemInfo.length; i++) {
            let config = this.interJson.itemInfo[i];
            let node = this.getChildForName(config.node);
            if (!node) { continue; }
            node.addComponent(LvItem_1).initItem(config, this);
        }
    }
    isTouchMove: boolean = false;  //是否按住移动
    touchStartPos: cc.Vec3 = null;
    /** 初始化触摸 */
    initTouch() {
        if (cc.sys.os == cc.sys.OS_WINDOWS) {
            this.huaNode.on(cc.Node.EventType.MOUSE_WHEEL, (touches: cc.Event.EventMouse) => {
                this.huaNode.getComponent(TouchScale).mouseWheelCall(touches);
            }, this);
        }
        this.huaNode.on(cc.Node.EventType.TOUCH_START, (touches: cc.Touch) => {
            this.isTouchMove = false;
            this.touchStartPos = cc.v3(touches.getLocation());
        }, this);
        this.huaNode.on(cc.Node.EventType.TOUCH_MOVE, (touchs: cc.Event.EventTouch) => {
            if (!this.touchStartPos || Tools.getDistance(this.touchStartPos, touchs.getLocation()) <= TOUCH_MOVE_LEN) { return; }
            this.isTouchMove = true;
            this.huaNode.getComponent(TouchScale).touchMoveCall(touchs);
        }, this);
        this.huaNode.on(cc.Node.EventType.TOUCH_END, (touch: cc.Event.EventTouch) => {
            if (!this.isTouchMove) {
                this.showErrorUI(touch.getLocation());
            }
            this.huaNode.getComponent(TouchScale).touchMoveEnd(touch);
            this.isTouchMove = false;
        }, this);

        this.huaNode.on(cc.Node.EventType.TOUCH_START, (touches: cc.Touch) => {

        }, this, true);
    }

    finishTween(finishStr: any, lvItem: LvItem) {
        if (typeof finishStr != "string") {
            if (finishStr.str) {   //人物说话
                this.sayNodeTween(finishStr);
            }
            return;
        }

        if (finishStr == "stopTime") {  //控制暂停时间
            EventManager.ins.emit(EVENT_NAME_ENUM.STOP_TIME);
            return;
        }
        if (finishStr == "startTime") {  //控制开始时间
            EventManager.ins.emit(EVENT_NAME_ENUM.START_TIME);
            return;
        }

        if (finishStr == "hideTipReturn") {  //隐藏返回提示按钮
            // EventManager.ins.emit(EVENT_NAME_ENUM.SHOW_TIP_BTN, false);
            // EventManager.ins.emit(EVENT_NAME_ENUM.SHOW_RETURN_BTN, false);
            return;
        }
        // if (finishStr.includes("title_")) {  //控制标题内容
        //     this.titleLab.string = finishStr.split("title_")[1];
        //     return;
        // }
        if (finishStr == "updateIsWin") {  //刷新是否胜利
            this.updateIsWin();
            return;
        }
        if (finishStr == "hideAllYuan") {   //隐藏所有绿圈
            for (let i = 0; i < this.interJson.itemInfo.length; i++) {
                let config = this.interJson.itemInfo[i];
                let node = this.getNodeForName(config.node);
                node.getComponent(LvItem_1).hideYuan();
            }
            return;
        }

        if (finishStr == "twoForOne") {  //合成
            if (lvItem.node.parent.children.length != 2) {
                return;
            }
            if (lvItem.node.parent.children[0].name.split("_")[1] == lvItem.node.parent.children[1].name.split("_")[1]) {
                this.runNodeTween(this.huaNode, this.getInterTwForName(lvItem.node.parent.children[0].name.split("_")[1] + "_Two").interTween);
            } else {
                let node1 = lvItem.node.parent.children[0];
                let node2 = lvItem.node.parent.children[1];
                Tools.setNodeParent(node1, this.huaNode);
                Tools.setNodeParent(node2, this.huaNode);
                node1.getComponent(LvItem).isClick = true;
                node2.getComponent(LvItem).isClick = true;
                cc.tween(node1).to(0.1, { position: node1.getComponent(LvItem).initPos, scale: 1 }).start();
                cc.tween(node2).to(0.1, { position: node2.getComponent(LvItem).initPos, scale: 1 }).start();
            }
            return;
        }
        /** 完成某个答案 */
        for (let i = 0; i < this.interJson.itemInfo.length; i++) {
            let config = this.interJson.itemInfo[i];
            if (config.node == finishStr) {
                let node = this.getNodeForName(config.node);
                if (!node) {
                    continue;
                }
                node.getComponent(LvItem_1).clickItem();
            }
        }
    }
    /** 返回关卡预制体  初始位置大小 */
    returnLvPre() {
        cc.tween(this.huaNode).to(0.3, { scale: this.huaNode.getComponent(TouchScale).minScale, position: cc.v3(0, 0) }).start();
    }


    /** 点击显示x号 */
    async showErrorUI(location: cc.Vec2) {
        let errorPrefab = await ResManager1.ins.loadRes("prefab/node/error", cc.Prefab, BUNDLE_TYPE_ENUM.GAME)
        let error = cc.instantiate(errorPrefab);
        this.viewBg.addChild(error);
        error.position = cc.v3(Tools.getToNodePosForWorld(location, this.viewBg));
    }

    /** 答案正确 */
    keyCorret(lvItem: LvItem_1) {
        let id = parseInt(lvItem.config.node.split("click_")[1]);
        if (id <= this.interJson.keyNum) {
            this.finishItemArr.push(lvItem);
        }
        let downItem: cc.Node = this.getItemForID(lvItem.config.id);
        downItem.getChildByName("lockSpr").active = false;
        downItem.getChildByName("itemSpr").active = true;
        downItem.getChildByName("itemLab").active = true;

        ActionTools._ins.shakeAni(downItem.getChildByName("itemSpr"), false, 10, 0.1);
        // Tools.setSpriteState( this.downContent.children[lvItem.config.id - 1] , 0 , true );

        let index = downItem.getSiblingIndex();
        let toX = 0;
        let tempIndex = Math.floor(this.downContent.parent.width / (downItem.width + this.downContent.getComponent(cc.Layout).spacingX));

        if (index < tempIndex / 2) {
            toX = -this.downContent.parent.width / 2;
        } else if (index >= (this.keyNum - tempIndex / 2)) {
            toX = this.downContent.parent.width / 2 - this.downContent.width;
        } else {
            toX = -this.downContent.parent.width / 2 - (index - (tempIndex / 2 - 0.5)) * (downItem.width + this.downContent.getComponent(cc.Layout).spacingX);
        }
        cc.tween(this.downContent).to(0.1, { x: toX }).start();

        let interTw = this.getInterTwForName("finishItem_" + this.finishItemArr.length);
        if (interTw) {  //完成几个后   执行Tween
            this.runNodeTween(this.node, interTw.interTween);
        }
        if (this.interJson["HandIsWin"] || this.interJson["sayUpdateIsWin"]) {   //手动控制不检测胜利
            return;
        }
        this.updateIsWin();
    }
    /** 打开提示按钮 */
    openTipBtn(downItem: cc.Node) {
        for (let i = 0; i < this.downContent.children.length; i++) {
            this.downContent.children[i].getChildByName("选中框").active = false;
        }
        if (this.keyBtn.node.active == true && downItem["config"].id == this.selectItemID) {
            this.keyBtn.node.active = false;
            this.selectItemID = 0;
            return;
        }
        this.keyBtn.node.active = true;
        downItem.getChildByName("选中框").active = true;
        this.selectItemID = downItem["config"].id;
        this.keyBtn.node.children[1].active = this.onLockItemArr.indexOf(this.selectItemID) < 0
    }
    /** 刷新是否过关 */
    updateIsWin() {
        if (this.finishItemArr.length >= this.interJson.keyNum) { //游戏胜利
            UIManager.ins.enabledClick(false);
            if (this.getInterTwForName("winGame")) {
                this.runNodeTween(this.viewBg, this.getInterTwForName("winGame").interTween);
            } else {
                this.scheduleOnce(() => UIManager.ins.showPop("WinUI", BUNDLE_TYPE_ENUM.GAME), 1);
            }
        }
    }
    isAddKey: boolean = false;
    /** 查看答案 */
    addAnswer() {
        // return;
        // if (this.isAddKey) { return; }
        // this.isAddKey = true;
        for (let i = 0; i < this.interJson.itemInfo.length; i++) {
            let config = this.interJson.itemInfo[i];
            if (config.id == this.selectItemID) {
                let node = this.getNodeForName(config.node);
                if (!node) {
                    continue;
                }
                node.getComponent(LvItem_1).showYuanNode();
            }
        }
    }
    /** 设置当前按页数 */
    setAlterNum(alterNum: number) {
        for (let i = 1; i <= this.interJson.changeNum; i++) {
            this.getChildForName("bg_" + i).active = false;
        }
        this.alterNum = alterNum
        this.getChildForName("bg_" + this.alterNum).active = true;
        this.returnLvPre();
    }
    lastSayAudio: string = null;
    /** 执行说话事件 */
    async sayNodeTween(sayInfo: any) {
        let tempT = 3;
        if (sayInfo.audio) {
            AudioManager1.stopAudioForName(this.lastSayAudio);
            let audioId = await AudioManager1.playAudio(sayInfo.audio.resUrl, sayInfo.audio.value, BUNDLE_TYPE_ENUM.LEVEL);
            this.lastSayAudio = sayInfo.audio.resUrl;
            tempT = cc.audioEngine.getDuration(audioId) + 0.2;
        }
        if (sayInfo.armAni) {
            this.runArmAni(sayInfo.armAni, sayInfo.armAni.shuo, sayInfo.armAni.node);
        }
        if (sayInfo.str) {
            this.showTipNodeLab(sayInfo.str, tempT, sayInfo);
        }
        return tempT;
    }
    /** 通过sayInfo执行龙骨动画 */
    runArmAni(armAni: any, aniName: string, sayNode?: cc.Node) {
        if (!armAni) { return; }
        let node = sayNode.parent;
        if (armAni.node) {
            node = this.getNodeForName(armAni.node);
        }
        node.getComponent(LvItem).playArmtureAni(aniName);
    }
    /** 显示提示文字  time 显示时间 */
    showTipNodeLab(str: string, time: number, sayInfo: any) {
        cc.Tween.stopAllByTarget(this.tipNode);

        let lab = this.tipNode.getComponentInChildren(cc.Label);
        if (str != "") {
            lab.string = str;
        }
        cc.tween(this.tipNode)
            .to(0.5, { opacity: 255 })
            .delay(time)
            .call(() => {
                if (sayInfo.armAni) {
                    this.runArmAni(sayInfo.armAni, sayInfo.armAni.daiji, sayInfo.armAni.node);
                }
                if (this.interJson["sayUpdateIsWin"]) {
                    this.updateIsWin();
                }
            }).to(0.5, { opacity: 0 }).start();
    }
    /**  通过id获取下方Item */
    getItemForID(id: number) {
        for (let i = 0; i < this.downContent.children.length; i++) {
            // const element = array[i];
            if (this.downContent.children[i]["config"] && this.downContent.children[i]["config"].id == id) {
                return this.downContent.children[i];
            }
        }
        return null;
    }
    /** 通过ID 获取Config */
    getConfigForID(id: number) {
        for (let i = 0; i < this.interJson.itemInfo.length; i++) {
            let config = this.interJson.itemInfo[i];
            if (config.id == id) {
                return config;
            }
        }
        return null;
    }

    get keyNum() {
        return this.interJson.keyNum;
    }
}
